package com.ruicar.afs.cloud.account.common.util;

import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.parser.ParserException;
import com.alibaba.druid.sql.parser.SQLParserUtils;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.text.MessageFormat;
import java.util.List;

import static com.alibaba.druid.sql.SQLUtils.toSQLString;

/**
 * @author infinity
 * @version 1.0
 * @date 2020/7/23 10:07
 * 校验并且格式化sql语句
 */
@Slf4j
public class SqlFormatUtil {
    public static String sqlFormat(String sql) {
        List<SQLStatement> statementList = null;
        SQLStatementParser parser = null;
        try {
            parser = SQLParserUtils.createSQLStatementParser(sql, "mysql");
            statementList = parser.parseStatementList();
        } catch (ParserException e) {
            log.error("SQL转换中发生了错误:{}",e.getMessage());
            Assert.isTrue(false, MessageFormat.format("sql语句:{0}",e.getMessage()));
        }
        return toSQLString(statementList, "mysql");
    }

}
